﻿# 从误差统计excel绘制出误差直方图
import math

import numpy as np
import pandas as pd
import sys
import matplotlib.pyplot as plt


def MyOtsu(x, bins):
    # 计算最小 最大 分割
    Min = min(x)
    Max = max(x)
    scale = (Max - Min) / bins
    gs = []
    ts = []
    for i in range(bins):
        gs.append(0)
        ts.append(Min + scale * i)

    w0 = 0
    u0 = 0
    w1 = 0
    u1 = 0
    u = 0

    # 计算平均
    for val in x:
        u += val
    u /= len(x)

    # 遍历每个分割
    for i, t in enumerate(ts):
        # 计算该分割的类间方差
        w0 = 0
        u0 = 0
        w1 = 0
        u1 = 0
        for val in x:
            if val < t:
                w0 += 1
                u0 += val
            else:
                w1 += 1
                u1 += val
        u0 = 0 if w0 == 0 else u0 / w0
        u1 = 0 if w1 == 0 else u1 / w1
        w0 /= len(x)
        w1 /= len(x)
        gs[i] = w0 * (u0 - u) * (u0 - u) + w1 * (u1 - u) * (u1 - u)

    # 查找最大的方差
    return ts[np.argmax(np.array(gs))]


# plt.rcParams['font.sans-serif'] = ['Simhei']  # 用来正常显示中文标签
plt.rcParams['font.sans-serif'] = ['Simsun']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
plt.rcParams['figure.figsize'] = [28, 10]
plt.rcParams.update(
    {
        'text.usetex': False,
        # 'font.family': 'stixgeneral',
        'mathtext.fontset': 'stix',
        "font.size": 28
    }
)

data = 0
if sys.argv.__len__() == 1:
    # path = input("输入csv路径")
    path = r"C:\Users\17616\Desktop\本科毕设\实验数据记录\2021-5-20\G0_0-F4-0520\G0_0-LD1I2\hist_info.csv"
    data = pd.read_csv(path, sep=',')
else:
    data = pd.read_csv(sys.argv[1], sep=',')

otsu_log = MyOtsu(x=data['log'], bins=400)
otsu_nolog = MyOtsu(x=data['no log'], bins=400)

plt.figure(figsize=(20, 10))
plt.suptitle(u"150pix*150pix高动态图直方图")

plt.subplot(1, 2, 1)

plt.hist(x=data['no log'], bins=400, color='steelblue')
plt.xlabel("像素值")
plt.ylabel("像素个数(个)")
plt.yscale("log")
plt.axvline(otsu_nolog, color='g')
plt.axvline(math.exp(otsu_log), color='r')
plt.subplot(1, 2, 2)

plt.hist(x=data['log'], bins=400, color='steelblue')
plt.xlabel("log(像素值)")
plt.ylabel("像素个数(个)")
plt.yscale("log")
plt.axvline(otsu_log, color='r')
plt.axvline(math.log(otsu_nolog), color='g')
# plt.axvline(math.log(MyOtsu(x=data['no log'], bins=400)), color='g')
plt.show()
